import 'package:citiesocial/_include.dart';
import 'package:citiesocial/ui/goods/hot_catalogue.dart';
import 'package:citiesocial/widgets/goods/history_goods.dart';

///首页-逛逛
class CatchUp extends BaseStatefulWidget {
  @override
  State<StatefulWidget> createState() => _CatchUpState();
}

class _CatchUpState extends BaseState<CatchUp> {
  var _alreadyLoadMore = false;
  final _bannerList = List<BannerEntity>();
  final _hotGoodsList = List<GoodsEntity>();
  final _activityList = List<IndexEntity>();
  final _themeList = List<ThemeEntity>();
  final _historyGoodsList = List<GoodsEntity>();
  final _categoryList = List<CategoryEntity>();

  void _loadData() async {
    _alreadyLoadMore = false;
    LoadingDialog.show(context);
    //banner
    _bannerList.clear();
    var banners = await HttpManager.indexBanner(context: context);
    if (banners.length > 0) {
      _bannerList.addAll(banners);
      setState(() {});
    }
    //即时排行
    _hotGoodsList.clear();
    var hotGoods = await HttpManager.getHotGoods(context: context, pagesize: 4);
    if (hotGoods.length > 0) {
      _hotGoodsList.addAll(hotGoods);
      setState(() {});
    }
    //活动名
    final deviceId = await getDeviceId();
    _activityList.clear();
    HttpManager.shopActivityType(context: context).then((types) async {
      if (types != null && types.length > 0) {
        for (ActivityTypeEntity type in types) {
          final a = await HttpManager.shopActivity(type.id, deviceId);
          if (a?.name != null || ((a?.list?.length ?? 0) > 0)) {
            _activityList.add(a); //活动名为空，或者列表为空，则认为没返回有效数据
          }
        }
        setState(() {});
      }
    });

    LoadingDialog.dismiss(context);
  }

  void _loadThemeAndHistoryAndHotCatalogueAndFindMore() async {
    if (!_alreadyLoadMore) {
      LoadingDialog.show(context);
      final deviceId = await getDeviceId();
      _alreadyLoadMore = true;
      HttpManager.themes(context: context, pagesize: 5).then((themes) {
        _themeList.clear();
        if (themes != null && themes.length > 0) {
          _themeList.addAll(themes);
          setState(() {});
        }
      });
      HttpManager.historyGoods(deviceId, context: context, pagesize: 3)
          .then((goods) {
        _historyGoodsList.clear();
        if (goods != null && goods.length > 0) {
          _historyGoodsList.addAll(goods);
          setState(() {});
        }
      });
      HttpManager.hotCategory(context: context).then((categories) {
        _categoryList.clear();
        if (categories != null && categories.length > 0) {
          _categoryList.addAll(categories);
          setState(() {});
        }
      });
      LoadingDialog.dismiss(context);
    }
  }

  void _onCategoryTap(int index) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) => GoodsByCatalogue(_categoryList[index]),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Configs.loadDelay, () {
      _loadData();
    });
  }

  @override
  Widget build(BuildContext context) {
    final _widgets = List<Widget>();
    if (_bannerList.length > 0) {
      _widgets.add(BannerIndex(_bannerList));
      _widgets.add(Container(
        decoration:
            BoxDecoration(shape: BoxShape.rectangle, color: Configs.background),
        height: 10.0,
      ));
    }
    if (_hotGoodsList.length > 0) {
      _widgets.add(
        FourGoods(
          '即时排行',
          goodsList: _hotGoodsList,
        ),
      );
    }
    if (_activityList.length > 0) {
      for (IndexEntity a in _activityList) {
        _widgets.add(IndexFlashCat(
          a.name,
          indexEntity: a,
        ));
      }
    }
    if (_themeList.length > 0) {
      _themeList.forEach((theme) {
        _widgets.add(ThemeGoods([theme], true));
      });
    }
    if (_historyGoodsList.length > 0) {
      _widgets.add(HistoryGoods(_historyGoodsList));
    }
    if (_categoryList.length > 0) {
      final List<Widget> history = List();
      for (int index = 0; index < _categoryList.length; index++) {
        history.add(ItemMenu(
          _categoryList[index].cat_name,
          leftIcon: _categoryList[index].cat_icon,
          leftIconEdge: 100.0,
          rightIcon: 'imgs/js_tabs_profile_img_more_g.png',
          onTap: () => _onCategoryTap(index),
        ));
      }
      _widgets.add(TitleAndMore(
        children: history,
        title: '热门分类',
        onMoreTap: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => HotCatalogue()));
        },
      ));
    }
    return DListView(
      itemBuilder: (_, index) => _widgets[index],
      itemCount: _widgets.length,
      onRefresh: () async => _loadData(),
      onLoadmore: () => _loadThemeAndHistoryAndHotCatalogueAndFindMore(),
    );
  }
}
